
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Select, Input, Button } from 'antd'
import { getStorageTypesSelection, getWarehouseStorage } from '@sagas/warehouse/stockManagement'
import ScheduleApplyModal from '@components/warehouse/modal/ScheduleApplyModal' // 调拨申请
import TakeStockModal from '@components/warehouse/modal/TakeStockModal' // 盘点
import BreakageModal from '@components/warehouse/modal/BreakageModal' // 报损
import DropdownMenu from "@common/presentational/DropdownMenu";
import { WarehouseSelect } from '@components/warehouse/WarehouseSelect'
import ParamsInput from "@common/presentational/ParamsInput";
import {priceFenToYuan, priceYuanToFen} from "@utils/priceConversion";
import { withRouter } from "react-router-dom";
import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from "@common/presentational/CustomizeTable";
import { getQuery, handleQueryEqual, setQuery } from "@utils/setUrlQuery";
function mapStateToProps(state) {
    const { stockManagement, warehouseManagement } = state
    return {
        storageTypesSelection: stockManagement.storageTypesSelection,
        warehouseStorage: stockManagement.warehouseStorage,
        selectedWarehouse: warehouseManagement.selectedWarehouse
    }
}

@connect(
    mapStateToProps,
    {
        getStorageTypesSelection,
        getWarehouseStorage
    }
)
@withRouter
class TimeInventory extends Component {
    constructor(props) {
        super(props)
        const {
            query = '',
            storageType = '',
            warehouseId = props.selectedWarehouse,
        } = getQuery(props.history)
        this.state = {
            tab: props.tab,
            query,
            storageType,
            warehouseId,
        }
        this.paginationInfo = {}
        this.tableRef = React.createRef()

        this.scheduleApplyModalRef = React.createRef()
        this.takeStockModalRef = React.createRef()
        this.breakageModalRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)
        this.showScheduleApplyModal = this.showScheduleApplyModal.bind(this)
        this.showBreakageModal = this.showBreakageModal.bind(this)
    }

    componentDidMount() {
        this.getSelection()
    }

    setUrlQuery() {
        const { current, pageSize } = this.paginationInfo
        const { tab, query, storageType, warehouseId, } = this.state
        const { history } = this.props
        let params = {
            tab,
            query,
            storageType,
            warehouseId, current, pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    getSelection() {
        const { warehouseId } = this.state
        warehouseId && this.props.getStorageTypesSelection({
            id: warehouseId,
            type: 2
        })
    }

    getTableInfo({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { query, storageType } = this.state
        const { warehouseId } = this.state
        this.setUrlQuery()
        const params = {
            id: warehouseId,
            queryType: 2,
            queryKeyword: query,
            pageNo: current,
            pageSize,
        }
        if (storageType) {
            params.queryTypeId = storageType
        }
        warehouseId && this.props.getWarehouseStorage(params)
    }

    handleRowOperation (record, type) {
        switch (type) {
            case 'take':
                this.showScheduleApplyModal(record)
                break;
            case 'break':
                this.showBreakageModal(record)
                break;
            default:
                break;
        }
    }

    getTableParams = () => {
        const { warehouseStorage } = this.props
        const columns = [
            {
                title: '名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '分类',
                dataIndex: 'type_name',
                key: 'type_name',
            },
            {
                title: '零售单价',
                dataIndex: 'price',
                key: 'price',
                render: text => priceFenToYuan(text) || '--'
            },
            {
                title: '库存',
                dataIndex: 'current_quantity',
                key: 'current_quantity',
            },
            {
                title: '操作',
                key: 'operation',
                width: '15%',
                render: (text, record) =>
                    <div className="flex-vertical-center">
                        <div onClick={this.showTakeStockModal.bind(this,record)} className="mgr-8 ft-hover">盘点</div>
                        <DropdownMenu
                            dropdownList={[{
                                key: 'take',
                                name: '调拨',
                            }, {
                                key: 'break',
                                name: '报损',
                            }]}
                            onClick={this.handleRowOperation.bind(this, record)}
                        >
                            <div className="ft-hover">更多</div>
                        </DropdownMenu>
                    </div>
            }
        ];
        const tableData = (warehouseStorage.data || []).map((warehouse, index) => ({
            ...warehouse,
            key: `warehouse_${index}`,
        }))
        return {
            columns,
            tableData,
            total: warehouseStorage.total
        }
    }

    initTable() {
        this.tableRef.current?.initPage()
    }

    handleValueChange(key, value) {
        if (key === 'dateRange') {
            this.setState({
                ...value
            }, this.initTable)
            return;
        }
        if (key === 'warehouseId') {
            this.setState({
                [key]: value
            },()=>{
                this.getSelection()
                this.getTableInfo()
            } )
            return;
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    showScheduleApplyModal(record) {
        const { warehouseId } = this.state
        this.scheduleApplyModalRef.current?.show({
            ...record,
            warehouseId
        })
    }

    showTakeStockModal(record) {
        const { warehouseId } = this.state
        this.takeStockModalRef.current?.show({
            ...record,
            warehouseId
        })
    }

    showBreakageModal(record) {
        const { warehouseId } = this.state
        this.breakageModalRef.current?.show({
            ...record,
            warehouseId
        })
    }


    render() {
        const { storageTypesSelection } = this.props
        const { columns, tableData, total } = this.getTableParams()
        const { storageType, query, warehouseId } = this.state
        return (
            <div>
                <div className="table-params page-params flex-vertical-center mgb-16">
                    <WarehouseSelect
                        className="mgl-16"
                        width='200px'
                        value={warehouseId}
                        onChange={this.handleValueChange.bind(this, 'warehouseId')}
                    />
                    <Select
                        className="mgl-16"
                        style={{ width: '200px' }}
                        placeholder="请选择商品分类"
                        allowClear={true}
                        value={storageType}
                        onChange={this.handleValueChange.bind(this, 'storageType')}
                        filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                    >
                        <Select.Option key='all' value='' >全部</Select.Option>
                        {storageTypesSelection.length ? (storageTypesSelection || []).map(item => {
                            return <Select.Option key={item.id} value={item.id} >{item.name}</Select.Option>
                        }) : null}
                    </Select>
                    <ParamsInput
                        className="mgl-16"
                        style={{ width: '200px' }}
                        value={query}
                        onChange={this.handleValueChange.bind(this, 'query')}
                        placeholder="商品/产品名称、编码搜索"
                    />
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="warehouseList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeTable
                            columns={columns}
                            dataSource={tableData || []}
                            pagination
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={total}
                        />
                    </div>
                </CustomizeTableProvide>
                <ScheduleApplyModal ref={this.scheduleApplyModalRef} callback={this.getTableInfo} />
                <TakeStockModal ref={this.takeStockModalRef} callback={this.getTableInfo} />
                <BreakageModal ref={this.breakageModalRef} callback={this.getTableInfo} />
            </div>
        )
    }
}

export default TimeInventory